package com.hctforgreen.greenservice.ui.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.VideoDownloadActivity;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.db.DBVideoDownloadManager;
import com.hctforgreen.greenservice.db.DBVideoManager;
import com.hctforgreen.greenservice.model.VideoTypeEntity.VideoDetailEntity.VideoPartEntity;
import com.hctforgreen.greenservice.utils.AsyncImageLoader;
import com.hctforgreen.greenservice.utils.AsyncImageLoader.ImageCallback;
import com.hctforgreen.greenservice.utils.DownloadUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.Md5Util;
import com.hctforgreen.greenservice.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.dns.reader.network.Util;

/**
 * 视频播放记录适配器
 * 
 * @author dhb 20141028
 * 
 */
public class VideoDownloadAdapter extends BaseAdapter implements
		OnItemClickListener {

	private Activity context;
	private List<VideoPartEntity> myList;
	private ListView listView;
	private List<String> doownloadIds;
	private Map<String, Long> fileSizeMap;

	private DBVideoDownloadManager dbVideoDownloadManager;

	public VideoDownloadAdapter(Activity context, List<VideoPartEntity> myList,
			ListView listView) {
		this.context = context;
		this.myList = myList;
		this.listView = listView;
		listView.setOnItemClickListener(this);
		doownloadIds = new ArrayList<String>();
		dbVideoDownloadManager = new DBVideoDownloadManager(context);
		fileSizeMap = new HashMap<String, Long>();
	}

	public int getCount() {
		return myList.size();
	}

	public Object getItem(int position) {
		return myList.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {

		ViewHolder holder = null;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(
					R.layout.item_video_download_layout, null);
			holder.img = (ImageView) convertView.findViewById(R.id.img_video);
			holder.name = (TextView) convertView
					.findViewById(R.id.tv_video_name);
			holder.fileSize = (TextView) convertView
					.findViewById(R.id.tv_file_size);
			holder.imgDelete = (ImageView) convertView
					.findViewById(R.id.img_delete);

			holder.percent = (TextView) convertView
					.findViewById(R.id.tv_percent);

			holder.imgDownload = (ImageView) convertView
					.findViewById(R.id.img_download);
			holder.downloadSpeed = (TextView) convertView
					.findViewById(R.id.tv_speed);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		final VideoPartEntity partEntity = myList.get(position);

		holder.name.setText(partEntity.videoName + "_" + partEntity.part);
		if (partEntity.picUrl != null && partEntity.picUrl.trim().length() > 0) {
			holder.img.setTag(Md5Util.md5(partEntity.picUrl));
			AsyncImageLoader imageLoader = new AsyncImageLoader();
			Drawable bitmap = imageLoader.loadDrawable(partEntity.picUrl,
					context, true, new ImageCallback() {

						@Override
						public void imageLoaded(Drawable imageDrawable,
								String imageUrl) {
							ImageView imageView = (ImageView) listView
									.findViewWithTag(Md5Util
											.md5(partEntity.picUrl));
							if (imageView != null && imageDrawable != null) {
								imageView.setImageDrawable(imageDrawable);
							}
						}
					});
			if (bitmap != null) {
				holder.img.setImageDrawable(bitmap);
			}

		} else {
			holder.img.setImageResource(R.drawable.ic_default_pic);
		}
		setFileSize(holder.fileSize, partEntity);

		holder.imgDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				AlertDialog.Builder builder = new Builder(context);
				builder.setMessage(
						context.getString(R.string.video_delete_message))
						.setTitle(
								context.getString(R.string.dialog_default_title_hint))
						.setNegativeButton(
								context.getString(R.string.dialog_cancel_hint),
								null)
						.setPositiveButton(
								context.getString(R.string.dialog_confirm_hint),
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										((VideoDownloadActivity) context)
												.getConnection()
												.cancelDownloadingUrl(
														partEntity.videoUrl);
										new Thread() {
											public void run() {
												File file = new File(
														VideoPartEntity
																.makeVideoFileName(
																		partEntity,
																		context));
												if (file.exists()) {
													file.delete();
												}
											};
										}.start();
										DBVideoDownloadManager downloadManager = new DBVideoDownloadManager(
												context);
										downloadManager.delete(partEntity);
										myList.remove(position);
										notifyDataSetChanged();
										// 发送更新通知
										Intent intent = new Intent();
										intent.setAction(HctConstants.RECEIVER_VIDEOSHELF_ACTIVITY_DOWNLOAD_UPDATE_PARTS);
										context.sendBroadcast(intent);
									}
								}).create().show();

			}
		});
		holder.percent.setTag(partEntity.id);
		holder.downloadSpeed.setTag(0L);
		if (dbVideoDownloadManager.haveDownloadEntity(partEntity)) {
			holder.imgDownload.setVisibility(View.GONE);
			holder.fileSize.setText(partEntity.fileSize);
		} else {
			holder.imgDownload.setVisibility(View.VISIBLE);
		}

		if (!doownloadIds.contains(partEntity.id)) {
			holder.fileSize.setText(partEntity.fileSize);
			holder.percent.setText("");
			holder.downloadSpeed.setText("");
		}
		holder.imgDownload.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				new Thread() {
					public void run() {
						HctController controller = new HctController(context);
						try {
							controller.addVideoDownloadCount(partEntity.id);
                            controller.addVideoDownloadRecord(partEntity.id, LoginResultStoreUtil.get(context).personId);
						} catch (Exception e) {
							e.printStackTrace();
						}
					};
				}.start();

				Util.doDownloadVideo(context, partEntity);
			}
		});

		return convertView;
	}

	private void setFileSize(final TextView fileSize,
			final VideoPartEntity partEntity) {
		String local = VideoPartEntity.makeVideoFileName(partEntity, context);
		File file = new File(local);
		if (file.exists()) {
			String localSize = Formatter.formatFileSize(context, file.length());
			fileSize.setText(localSize + "/" + partEntity.fileSize);
		} else {
			fileSize.setText(partEntity.fileSize);
		}

	}

	class ViewHolder {
		ImageView img;//
		TextView name;// 名称
		TextView fileSize;// 已下载文件大小/文件大小
		TextView downloadSpeed;// 下载速度
		TextView percent;// 下载完成度
		ImageView imgDelete;// 删除
		ImageView imgDownload;// 下载
	}

	public void updateVideosLayout(String downloadId, int progress) {
		doownloadIds.add(downloadId);
		for (int i = 0; i < myList.size(); i++) {
			View convertView = listView.getChildAt(i + 1);// 有headview
			final VideoPartEntity partEntity = getFromListById(downloadId);
			// convertView.fin
			if (convertView == null) {
				continue;
			}
			final TextView percent = (TextView) convertView
					.findViewById(R.id.tv_percent);
			if (percent == null) {
				continue;
			}
			final TextView speed = (TextView) convertView
					.findViewById(R.id.tv_speed);
			final TextView fileSize = (TextView) convertView
					.findViewById(R.id.tv_file_size);
			final String videoId = (String) percent.getTag();
			if (downloadId != null && downloadId.equals(videoId)) {
				if (progress == 99 || progress == 100) {
					doownloadIds.remove(downloadId);
					fileSizeMap.remove(downloadId);
					convertView.findViewById(R.id.img_download).setVisibility(
							View.GONE);
					percent.setText("");
					speed.setText("");
					fileSize.setText(partEntity.fileSize);
					partEntity.downloadState = HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_DONE;
					DBVideoDownloadManager dbVideoDownloadManager = new DBVideoDownloadManager(
							context);
					dbVideoDownloadManager.updatepartEntity(partEntity);
				} else if (progress == -1) {
					percent.setText(context.getResources().getString(
							R.string.download_waiting_hint));
					speed.setText("");
				} else {
					percent.setText(progress + "/%");
					percent.invalidate();
					System.out.println(percent.getText());
					File file = new File(VideoPartEntity.makeVideoFileName(
							partEntity, context));
					if (file.exists()) {
						Long dp = (Long) (fileSizeMap.get(downloadId) == null ? 0L
								: fileSizeMap.get(downloadId));
						if (dp > file.length()) {
							dp = file.length();
						}
						fileSizeMap.put(downloadId, file.length());
						Long ds = (Long) ((file.length() - dp) / 2);
						if (ds == 0L) {
							speed.setText("");
						} else {
							speed.setText(Formatter.formatFileSize(context, ds)
									+ "/s");
						}
						fileSize.setText(Formatter.formatFileSize(context,
								file.length())
								+ "/" + partEntity.fileSize);
					}
				}

			}
		}
		// notifyDataSetChanged();
	}

	private VideoPartEntity getFromListById(String id) {
		VideoPartEntity entity = new VideoPartEntity();
		if (id == null || myList == null || myList.isEmpty()) {
			return entity;
		}

		for (int i = 0; i < myList.size(); i++) {
			if (id.equals(myList.get(i).id)) {
				entity = myList.get(i);
			}
		}

		return entity;

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		final VideoPartEntity entity = myList.get(position - 1);// 有headView
		DBVideoDownloadManager dbVideoDownloadManager = new DBVideoDownloadManager(
				context);
		if (dbVideoDownloadManager.haveDownloadEntity(entity)) {// 已下载
			String fileName = VideoPartEntity
					.makeVideoFileName(entity, context);
			if (fileName != null && new File(fileName).exists()) {// 文件存在
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Uri data = Uri.parse("file://" + fileName);
				intent.setDataAndType(data, "video/*");
				context.startActivity(intent);
			} else {// 文件不存在，视频保存为未下载状态
				entity.downloadState = "";
				dbVideoDownloadManager.updatepartEntity(entity);
				notifyDataSetChanged();
				// 发送更新通知
				Intent intent = new Intent();
				intent.setAction(HctConstants.RECEIVER_VIDEOSHELF_ACTIVITY_DOWNLOAD_UPDATE_PARTS);
				context.sendBroadcast(intent);

				DownloadUtil downloadUtil = new DownloadUtil();
				downloadUtil.makeSureDownloadDiaolg(context, entity);
			}

		} else {

			AlertDialog.Builder builder = new Builder(context);
			builder.setMessage(
					context.getString(R.string.video_download_message))
					.setTitle(
							context.getString(R.string.dialog_default_title_hint))
					.setNegativeButton(
							context.getString(R.string.video_download_play_now),
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									if (!Utils.isWifiNetworkConnected(context)) {
										AlertDialog.Builder builder = new Builder(
												context);
										builder.setMessage(
												context.getString(R.string.video_dialog_network_3g_wran))
												.setTitle(
														context.getString(R.string.dialog_default_title_hint))
												.setNegativeButton(
														context.getString(R.string.dialog_cancel_hint),
														null)
												.setPositiveButton(
														context.getString(R.string.dialog_confirm_hint),
														new DialogInterface.OnClickListener() {

															@Override
															public void onClick(
																	DialogInterface dialog,
																	int which) {
																insertDBAndAddCount(entity);
																Intent intent = new Intent(
																		Intent.ACTION_VIEW);
																Uri uri = Uri
																		.parse(entity.videoUrl);
																intent.setDataAndType(
																		uri,
																		"video/*");
																intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
																context.startActivity(intent);
															}
														}).create().show();
									} else {
										Intent intent = new Intent(
												Intent.ACTION_VIEW);
										Uri uri = Uri.parse(entity.videoUrl);
										intent.setDataAndType(uri, "video/*");
										intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
										context.startActivity(intent);
									}
								}
							})
					.setPositiveButton(
							context.getString(R.string.video_download_download_first),
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Util.doDownloadVideo(context, entity);
								}
							}).create().show();

		}

	}

	private void insertDBAndAddCount(final VideoPartEntity partEntity) {
		new Thread() {
			public void run() {// 插入本地数据库，历史播放记录
				try {
					DBVideoManager dbVideoManager = new DBVideoManager(context);
					dbVideoManager.add(partEntity);

					HctController controller = new HctController(context);
					controller.addVideoPalyCount(partEntity.id);// 增加统计
                    controller.addVideoPlayRecord(partEntity.id,LoginResultStoreUtil.get(context).personId);
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();

	}
}